package com.xbn.xbnmall.product.exception;

import com.xbn.common.exception.BizCodeEnume;
import com.xbn.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author XBN
 * @date 2020/7/9 8:55
 * @email 78742541@qq.com
 */
@Slf4j

@RestControllerAdvice(basePackages = "com.xbn.xbnmall.product.controller")
public class XbnmallExceptionControllerAdvice {
    /*
    * 统一处理数据验证异常
    * */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errors=new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            //获取错误提示
            String message=item.getDefaultMessage();
            String field=item.getField();
            errors.put(field,message);
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errors);
    }
    /*
    * 处理任意类型的异常，其它精确异常都没有匹配到才会到这个处理中
    * */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){
        log.error("错误:",e);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }


}
